package mobi.greenplate.client.connect;

import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpResponse;

/**
 *
 * @author dmakariev
 */
public class DefaultResponseHandler implements ResponseHandler {

    private HttpResponse httpResponse;

    public void setHttpResponse(HttpResponse response) {
        this.httpResponse = response;
    }

    protected HttpResponse getHttpResponse() {
        return httpResponse;
    }

    public String getLocation() {
        try {
            return getHttpResponse().getLastHeader("Location").getValue();
        } catch (Exception e) {
            throw new RuntimeException(this.getClass().getName()+".getLocation failed !", e);
        }
    }

    public Long getId() {
        try {
            return Long.valueOf(extractId(getLocation()));
        } catch (Exception e) {
            throw new RuntimeException(this.getClass().getName()+".getLocation getId !", e);
        }
    }

    private static String extractId(String location) {
        final String REGExp_ID = "^.+/(\\d+)$";
        final Pattern p = Pattern.compile(REGExp_ID);
        final Matcher m = p.matcher(location);
        if (m.find()) {
            final String extracted = m.group(1);
            return extracted;
        } else {
            throw new IllegalArgumentException(" not correct location = " + location);
        }
    }

    public void handleContent(InputStream inputStream, long contentLength){
        //do nothing this should be implemented by the extending class
    }
}
